﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ClosedXML.Excel;

namespace 文件查找
{
    public partial class MainWindow : Window
    {
        private ObservableCollection<FileInfoItem> foundFiles = new ObservableCollection<FileInfoItem>();
        private string lastExcelFilePath = string.Empty;

        public MainWindow()
        {
            InitializeComponent();
            FilesDataGrid.ItemsSource = foundFiles;
        }

        private async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            string folderPath = FolderPathTextBox.Text;
            string fileFormat = FileFormatTextBox.Text;

            if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
            {
                MessageBox.Show("请输入有效的文件夹路径！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (string.IsNullOrEmpty(fileFormat))
            {
                MessageBox.Show("请输入文件格式！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            foundFiles.Clear();
            IsEnabled = false;

            try
            {
                await System.Threading.Tasks.Task.Run(() =>
                {
                    var files = Directory.GetFiles(folderPath, fileFormat, SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        var fileInfo = new FileInfo(file);
                        Dispatcher.Invoke(() =>
                        {
                            foundFiles.Add(new FileInfoItem
                            {
                                Path = file,
                                Size = FormatFileSize(fileInfo.Length),
                                ModifiedDate = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        });
                    }
                });

                MessageBox.Show($"找到 {foundFiles.Count} 个文件！", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索文件时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsEnabled = true;
            }
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            var folderBrowser = new FolderBrowserWindow();
            folderBrowser.Owner = this;

            if (folderBrowser.ShowDialog() == true)
            {
                FolderPathTextBox.Text = folderBrowser.SelectedPath;
            }
        }



        private void ExportToExcelButton_Click(object sender, RoutedEventArgs e)
        {
            if (foundFiles.Count == 0)
            {
                MessageBox.Show("没有可导出的数据！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog
            {
                Filter = "Excel文件|*.xlsx",
                DefaultExt = "xlsx",
                Title = "保存Excel文件"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (var workbook = new XLWorkbook())
                    {
                        var worksheet = workbook.Worksheets.Add("文件列表");
                        worksheet.Cell(1, 1).Value = "文件路径";
                        worksheet.Cell(1, 2).Value = "文件大小";
                        worksheet.Cell(1, 3).Value = "修改时间";

                        for (int i = 0; i < foundFiles.Count; i++)
                        {
                            worksheet.Cell(i + 2, 1).Value = foundFiles[i].Path;
                            worksheet.Cell(i + 2, 2).Value = foundFiles[i].Size;
                            worksheet.Cell(i + 2, 3).Value = foundFiles[i].ModifiedDate;
                        }

                        worksheet.Columns().AdjustToContents();
                        workbook.SaveAs(saveFileDialog.FileName);
                        lastExcelFilePath = saveFileDialog.FileName;
                    }

                    MessageBox.Show("导出成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出Excel文件时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void OpenExcelButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(lastExcelFilePath) || !File.Exists(lastExcelFilePath))
            {
                MessageBox.Show("请先导出Excel文件！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = lastExcelFilePath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开Excel文件时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB" };
            int order = 0;
            double len = bytes;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len = len / 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }
    }

    public class FileInfoItem
    {
        public string Path { get; set; } = string.Empty;
        public string Size { get; set; } = string.Empty;
        public string ModifiedDate { get; set; } = string.Empty;
    }
}
